import fitz
import os

def real_pdf_stretch(input_path, output_path, x_scale=1.2):
    """真正实现PDF内容横向拉伸（兼容各版本PyMuPDF）"""
    try:
        # 创建输出目录
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        
        # 打开原始文档
        src_doc = fitz.open(input_path)
        dst_doc = fitz.open()
        
        print(f"🔧 正在处理: {os.path.basename(input_path)}")
        print(f"📑 总页数: {len(src_doc)}")
        print("🔄 转换进度:")

        for page_num in range(len(src_doc)):
            src_page = src_doc[page_num]
            
            # 计算新页面尺寸
            original_width = src_page.rect.width
            original_height = src_page.rect.height
            new_width = original_width * x_scale
            
            # 创建新页面
            dst_page = dst_doc.new_page(width=new_width, height=original_height)
            
            # 核心：通过调整目标矩形实现缩放
            src_rect = src_page.rect  # 原始页面区域
            dst_rect = fitz.Rect(0, 0, new_width, original_height)  # 目标区域
            
            # 兼容性写入方法
            dst_page.show_pdf_page(
                dst_rect,        # 目标区域（已放大）
                src_doc,         # 源文档
                page_num,        # 源页码
                clip=src_rect,   # 源内容区域
                keep_proportion=False
            )
            
            print(f"  页 {page_num+1}: {original_width:.1f}pt → {new_width:.1f}pt")

        # 保存文档
        dst_doc.save(output_path)
        print(f"\n✅ 转换完成！保存至: {os.path.abspath(output_path)}")

    except Exception as e:
        print(f"\n❌ 转换失败: {str(e)}")
    finally:
        src_doc.close()
        dst_doc.close()

# 使用示例
if __name__ == "__main__":
    # 多栏
    path = "pdfs/00a78ced0120c61a1985c3b7832af76d_GSHNDQ201017_9.pdf" 
    # 多列
    path = "pdfs/00b2c55915da92ec33d1bfd30f32e9ef_YLNQ201917_53.pdf"
    # 网格
    path = "pdfs/00ce9c485eff2145c6c5fa9af35865a0_YLQC202005_69.pdf"
    # 漫画
    path = "pdfs/0a4c97852e19c2748410ed4535f06aa6_YLDQ202211_73.pdf"
    real_pdf_stretch(
        input_path=path,
        output_path="output/stretched_YLDQ202211_73.pdf",
        x_scale=1.2
    )